import {defineStore} from 'pinia';
import curdUtils from "/@/stores/ums/customer/curdUtils";
import {umsMemberStateApi as api} from "/@/api/ums/member/stateApi"
import {ElMessage} from 'element-plus';


/**
 * 客户类型
 */
export const customerTypeCache = defineStore('customerType', {
    state: (): any => ({
        // 列表
        list: [],
        // get 加载的锁
        lock: false,
        // 类型
        type: 2,
        // 标题
        title: '客户类型'
    }),
    actions: {

        /**
         * 添加
         * @param domain 添加数据对象
         */
        async add(domain: any): Promise<boolean> {
            if (!domain) {
                return false
            }
            // 添加类型
            domain['type'] = this.type;
            // 保存到数据库
            return await this.addData(domain, api, this.loadList, this.title)
        },

        /**
         * 获取
         * 1、不一定立即能获取到
         * 2、因为有异步加载，返回的对象是引用
         */
        getList(): Array<any> {
            // 检查是否有数据
            if (this.isLoad(this.lock, this.list)) {
                this.lock = true
                this.loadList()
            }
            return this.list
        },

        /** 加载 */
        async loadList() {
            try {
                const params = {'type': this.type};
                const {data} = await api().query(params);
                // 清除重新加载
                this.checkReset(this.list)
                // 增量加载 - 直接赋值会导致引用失效
                this.list.push(...data);
            } catch (e: any) {
                console.log('获取' + this.title + '列表异常捕获\n', e);
                ElMessage.error(e.message)
            }
            this.lock = false
        },

        /**
         * 批量修改显示或隐藏
         * @param ids 需要显示 ID 空则全部不显示
         */
        async batchVisibleByIds(ids: any): Promise<boolean> {
            return await this.doBatchVisible(ids, {'type': this.type}, api, this.loadList, this.title)
        },

        init() {
            if (this.isLoad(this.lock, this.list)) {
                this.lock = true
                this.loadList()
            }
        },

        // 公共方法
        ...curdUtils
    },

});



